package com.laiat.yamba;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;

import com.laiat.yamba.activity.StatusActivity;

public class StatusData {
	private static final String TAG = StatusActivity.class.getSimpleName();

	private static final String DB_NAME = "timeline.db";
	private static final int DB_VERSION = 1;
	public static final String TABLE = "timeline";
	public static final String C_ID = BaseColumns._ID;
	public static final String C_CREATED_AT = "created_at";
	public static final String C_SOURCE = "source";
	public static final String C_TEXT = "txt";
	public static final String C_USER = "user";
	
	public static final String GET_ALL_ORDER_BY = C_CREATED_AT + " DESC";
	
	private static final String[] MAX_CREATED_AT_COLUMNS = { "max("
		+ StatusData.C_CREATED_AT + ")"
	};
	
	private static final String[] DB_TEXT_COLUMNS = { C_TEXT };
	
	private final DbHelper dbHelper;

	public DbHelper getDbHelper() {
		return dbHelper;
	}

	public StatusData(Context context) {
		this.dbHelper = new DbHelper(context);
		Log.i(TAG, "initialized data");
	}
	
	public void close() {
		this.dbHelper.close();
	}
	
	public void insertOrIgnore(ContentValues values) {
		Log.d(TAG, "insertOrIgnore on " + values);
		SQLiteDatabase db = this.dbHelper.getWritableDatabase();
		try {
			//does not work on Android 2.1-update1
//			db.insertWithOnConflict(TABLE, null, values, SQLiteDatabase.CONFLICT_IGNORE);
	
			//works on Android 2.1
			db.insertOrThrow(TABLE, null, values);
		} catch(SQLException e) {
			//Ignore exception since should be duplicates
			Log.d(TAG, "value=" + values.toString(), e);

		} catch(RuntimeException e) {
			Log.d(TAG, "value=" + values.toString(), e);
			
		} finally {
			db.close();
		}
		
	}
	
	public void delete() {

		Log.d(TAG, "delete all");
		SQLiteDatabase db = this.dbHelper.getWritableDatabase();
		try {
			db.delete(TABLE, null, null);
			
			//fire off broadcast to refresh timeline view
			Intent intent = new Intent();
			intent.setAction(UpdaterService.BROADCAST_UPDATE_TIMELINE_ACTION_NAME);
			
			this.dbHelper.context.sendBroadcast(intent);
			
		} catch(SQLException e) {
			//Ignore exception since should be duplicates
			Log.d(TAG, "delete failed", e);

		} catch(RuntimeException e) {
			Log.d(TAG, "delete failed", e);
			
		} finally {
			db.close();
		}

	}
	
	public Cursor getStatusUpdates() {
		SQLiteDatabase db = this.dbHelper.getReadableDatabase();
		return db.query(TABLE, null, null, null, null, null, GET_ALL_ORDER_BY);
	}
	
	public long getLatestStatusCreatedAtTime() {
		SQLiteDatabase db = this.dbHelper.getReadableDatabase();
		try {
			Cursor cursor = db.query(TABLE, MAX_CREATED_AT_COLUMNS, null, null, null, null, null, "1");
			try {
				return cursor.moveToNext() ? cursor.getLong(0) : Long.MIN_VALUE;
			} finally {
				cursor.close();
			}
		} finally {
			db.close();
		}
	}
	
	public String getStatusTextById(long id) {
		SQLiteDatabase db = this.dbHelper.getReadableDatabase();
		try {
			Cursor cursor = db.query(TABLE, DB_TEXT_COLUMNS, C_ID + "=" + id, null, null, null, null);
			try {
				return cursor.moveToNext() ? cursor.getString(0) : null;
			} finally {
				cursor.close();
			}
		} finally {
			db.close();
		}
	}
	
	public class DbHelper extends SQLiteOpenHelper {

		private Context context;
		
		//Constructor
		public DbHelper(Context context) {
			super(context, DB_NAME, null, DB_VERSION);
			this.context = context;
		}


		//Called only once, first time the DB is created
		@Override
		public void onCreate(SQLiteDatabase db) {
			String sql = "create table " + TABLE + " (" + C_ID + " int primary key, "
				+ C_CREATED_AT + " int, " + C_SOURCE + " text, " + C_USER + " text, " + C_TEXT + " text)";
			
			db.execSQL(sql);
			
			Log.d(TAG, "onCreated sql: " + sql);
		}


		//Called whenever newVersion != oldVersion
		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			//Typically do ALTER TABLE statements, but .. we're just in development, so:
			
			db.execSQL("drop table if exists " + TABLE);  //drops the old database
			Log.d(TAG, "onUpdated");
			onCreate(db);  // run onCreate to get new database
			
		}
		
		public Context getContext() {
			return context;
		}

	}
}
